package com.li.configserve.config.datasource;

import com.li.configserve.domain.properties.MysqlProperties;
import com.li.toolkit.constant.LogConst;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.sql.Connection;

/**
 * @description: HikariCpConfig数据连接池
 * @author: Lidong
 * @time: 2020/6/21 14:38
 **/
@SuppressWarnings("ALL")
@Configuration
public class HikariCpConfig {

    private final Logger logger = LoggerFactory.getLogger(HikariCpConfig.class);

    public static DataSource dataSource;

    /**
     * 注入Mysql的属性信息
     */
    @Autowired
    MysqlProperties mysqlProperties;


    public static void setDataSource(DataSource dataSource) {
        HikariCpConfig.dataSource = dataSource;
    }

    /**
     * 实例化HikariConfig连接池,返回一个连接
     *
     * @return
     */
    @Bean
    public Connection connection()  {
        try {
            HikariConfig hikariConfig = new HikariConfig();
            hikariConfig.setDriverClassName(mysqlProperties.getDrivername());
            hikariConfig.setJdbcUrl(mysqlProperties.getJdbcurl());
            hikariConfig.setUsername(mysqlProperties.getUsername());
            hikariConfig.setPassword(mysqlProperties.getPassword());
            HikariDataSource hikariDataSource = new HikariDataSource(hikariConfig);
            setDataSource(hikariDataSource);
            Connection connection = dataSource.getConnection();
            logger.info(LogConst.LOG_SUCCESS_PREFIX + "HikariConfig初始化结束...");
            return connection;
        } catch (Exception e) {
            logger.error(LogConst.LOG_FAILURE_PREFIX + e.getMessage());
            return null;
        }
    }
}
